package com.ts.api.module.product.service.impl;

import com.gitee.apanlh.util.date.DateUtils;
import com.ts.api.common.constant.BizEnum;
import com.ts.api.common.context.ChannelContext;
import com.ts.api.common.context.ChannelUserContext;
import com.ts.api.exp.BizException;
import com.ts.api.module.channel.entity.po.ChannelUserProductMatchPO;
import com.ts.api.module.product.dao.ProductUserMatchDao;
import com.ts.api.module.product.entity.po.ProductUserMatchPO;
import com.ts.api.module.product.entity.qo.ProductPlanLimitQO;
import com.ts.api.module.product.service.ProductUserMatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductUserMatchServiceImpl implements ProductUserMatchService {

    @Autowired
    private ProductUserMatchDao productUserMatchDao;

    @Override
    @Transactional(readOnly = true)
    public Integer countPlanApplyTotal(ProductPlanLimitQO productPlanLimitQO) {
        return productUserMatchDao.countPlanApplyTotal(productPlanLimitQO);
    }

    @Override
    @Transactional(readOnly = true)
    public List<ProductUserMatchPO> listByUser(Long userId) {
        return productUserMatchDao.listByUser(userId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<ChannelUserProductMatchPO> listProductMatchByUserId(Long userId) {
        return productUserMatchDao.listProductMatchByUserId(userId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<ChannelUserProductMatchPO> listUserProductMatchLocalCrmByUserId(Long userId) {
        return productUserMatchDao.listProductMatchLocalCrmByUserId(userId);
    }

    @Override
    public int insertUserProductMatch(Long productId) {
        ChannelUserProductMatchPO channelUserProductMatchPO = new ChannelUserProductMatchPO();
        channelUserProductMatchPO.setLoanProductId(productId);
        channelUserProductMatchPO.setLoanUserId(ChannelUserContext.getId());
        channelUserProductMatchPO.setCreateTime(DateUtils.currentTime());
        channelUserProductMatchPO.setLoanChannelId(ChannelContext.getId());

        try {
            return productUserMatchDao.insertUserProductMatch(channelUserProductMatchPO);
        } catch (DuplicateKeyException e) {
            throw new BizException(BizEnum.MATCH_DUPLICATE);
        }
    }

}
